/**
 * Created by RickyTT on 14-1-28.
 */

var db1Obj = require('./db');
var iMysql = require('./sqldb');
var async = require('async');

function Post(post){
    this.id = post.id;
    this.userId = post.userId;
    this.userName = post.userName;
    this.createTime = post.createTime;
    this.updateTime = post.updateTime;
    this.blog = post.blog;
}

module.exports = Post;

Post.getByNum = function getByNum(num,callback){
    db1Obj.sql('select * from post order by updateTime DESC limit '+num+'',function(err,result){
        if(err || !result){
            callback(err,result);
        }else{
            var posts = [];
            result.forEach(function(post,index){
                var newPost = new Post(post);
                posts.push(newPost);
            });
            callback(err,posts);
        };
    });
};


Post.insert = function insert(userId,userName,blog,callback){
    var trans = iMysql.transaction();

    trans.sql('insert into post (userId,userName,blog) values ('+userId+',"'+userName+'","'+blog+'")',function(err,result){
        if(err){
            callback(err,result);
        }else{
            trans.commit(function(err){
                if (err) {
                    callback(err,result);
                    throw err;
                } else {
                    callback(err,result);
                };
            });
        };
    });
};


Post.deleteById = function deleteById(id,callback){
    var trans = iMysql.transaction();
    trans.sql('delete from post where id = '+id+'',function(err,result){
        if(err){
            callback(err,result);
        }else{
            trans.commit(function(err){
                if (err) {
                    callback(err,result);
                    throw err;
                } else {
                    callback(err,result);
                };
            });
        };
    });
};


